#include "images.h"

#include <assert.h>
#include <stdlib.h>

#include "global.h"
#include "data.h"
#include "ui.h"


// List of images to load
struct ImageNames {
	int i;
	char* file;
	_Bool mirror;
} image_names[] = { 
	{ TITLE, "title.png", false },
	{ DEFAULT_OPTION, "default_option.png", false },
	{ PANEL_OPENER, "panel_opener.png", false },
	{ TOOLBAR_SELECT, "toolbar_select.png", false },
};


// Mirror a image horizontaly
static void mirror_image(SDL_Surface* sf)
{
	int x, y;
	Uint8* pixels = ((Uint8*)sf->pixels);

	if(SDL_MUSTLOCK(sf))
		if(SDL_LockSurface(sf) == -1)
			ui_error("Error locking surface: %s", SDL_GetError());

	for(y=0; y<sf->h; y++)
		for(x=0; x<(sf->w/2); x++)
		{
			Uint8 swp = pixels[(y * sf->pitch) + x];
			pixels[(y * sf->pitch) + x] = pixels[(y * sf->pitch) + sf->w - x - 1];
			pixels[(y * sf->pitch) + sf->w - x - 1] = swp;
		}

	if(SDL_MUSTLOCK(sf))
		SDL_UnlockSurface(sf);
}


// Load a image from the disk.
static SDL_Surface* load_image(char* filename, _Bool mirror)
{
	SDL_Surface* sf = IMG_Load(filename);

	// validate image
	if(!sf)
		ui_error(_("Image %s not found."), filename);
	if(sf->format->BitsPerPixel != 8)
		ui_error(_("Image %s expected to be 8-bit."), filename);

	// TODO - mirror the image, if asked
	if(mirror)
		mirror_image(sf);

	// set transparent color
	int status = SDL_SetColorKey(sf, SDL_SRCCOLORKEY|SDL_RLEACCEL, 255);
	if(status == -1)
		ui_error(_("Error setting image colorkey."));

	return sf;
}


// Load all images needed for the game.
void load_images()
{
	int i;
	int num_images = sizeof(image_names)/sizeof(struct ImageNames);

	images = malloc(sizeof(SDL_Surface*) * NUM_IMAGES);
	for(i=0; i<num_images; i++)
		images[image_names[i].i] = 
			load_image(datapath(image_names[i].file),
					image_names[i].mirror);
}
